#include <stdio.h>
#include <stdlib.h>

#define MAX 41

int main(void)
{
    char words[MAX];
    FILE * fp;

    if ((fp = fopen("wordy", "a+")) == NULL)
    {
        fprintf(stderr, "Can't open \"wordy\" file");
        exit(EXIT_FAILURE);
    }

    puts("Enter words to add to the file; press the # key at the beginning of a line to terminate.");
    while (fscanf(stdin, "%40s", words) == 1 && words[0] != '#')
        fprintf(fp, "%s\n", words);
    
    puts("File contents: ");
    rewind(fp);
    while (fscanf(fp, "%s", words) == 1)
        fprintf(stdout, "%s\n", words);
    
    if (fclose(fp) != 0)
        fprintf(stderr, "Error closing file\n");
    
    printf("Done!");

    return 0;
}